<?php

//require_once(dirname(__FILE__) . '/EventDispatcher.php');
require_once(dirname(__FILE__) . '/Deferred.php');

/**
 * Description of DeferredList
 * @link http://javascript.ru/unsorted/async/deferred-deep
 * @link http://twistedmatrix.com/documents/8.1.0/api/twisted.internet.defer.DeferredList.html
 * @author Gvozd
 */
class DeferredList extends Deferred {

    public $deferredList = array();
    public $isDeferred = array();

    /**
     *
     * @param array $deferredList
     * @param int $fireOnOneCallback unsupported
     * @param int $fireOnOneErrback unsupported
     * @param int $consumeErrors  unsupported
     */
    public function __construct($deferredList /*, $fireOnOneCallback=0, $fireOnOneErrback=0, $consumeErrors=0*/) {
        if (!is_array($deferredList)) {
            throw new DieException('Not Deferred');
        }
        $_this = $this;
        foreach ($deferredList as $key => $value) {
            $this->deferredList[$key] = $value;
            if (is_a($value, 'Deferred')) {
                $this->isDeferred[] = $key;
                $value->addBoth(function($result) use($_this, $key) {
                    $_this->deferredList[$key] = $result;
                    $k = array_search($key, $_this->isDeferred);
                    unset($_this->isDeferred[$k]);
                    $_this->check();
                    return $result;
                });
            } else {
                
            }
        }
        $this->check();
    }

    public function check() {
        if(empty ($this->isDeferred)) {
            $this->callback($this->deferredList);
        }
    }

}